import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {AddUserPage, AddUser} from './addUser';
import {Router} from '@angular/router';
import {UserService} from '../user/user.service';
import {BaseComponent} from '../common/base.component';
import {Md5} from 'ts-md5/dist/md5';
import {until} from 'selenium-webdriver';
import elementIsDisabled = until.elementIsDisabled;

@Injectable()
export class AddUserService extends BaseComponent {
  public token: string;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'user/getUserData'; // URL to web api
  private hostUrlAddUser = ParamConfig.HTTP_WEB_HOST_URL + 'user/saveUser';
  private hostUrlUpdateUser = ParamConfig.HTTP_WEB_HOST_URL + 'user/updateUser';
  private hostUrlDeleteUser = ParamConfig.HTTP_WEB_HOST_URL + 'user/deleteUser';
  private hostUrlAllRole = ParamConfig.HTTP_WEB_HOST_URL + 'user/allotRole'; // 分配角色
  private hostUrlGetRole = ParamConfig.HTTP_WEB_HOST_URL + 'role/listRole'; // 获取角色列表
  private hostUrlSureId = ParamConfig.HTTP_WEB_HOST_URL + 'user/alreadAllotRole'; // 获取用户已分配的角色id
  constructor(private http: Http, private userService: UserService, private router: Router) {
    super();
  };

// 查询用户
  getUser(page): Promise<any> {
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new AddUserPage();
            pagedata.addUser = body as AddUser[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
        }
      )
      .catch(this.handleError);
  }

  // 增加用户
  addUserinfo(addUser: AddUser): Promise<any> {
    const pwdMd5 = Md5.hashStr(addUser.password).toString();
    this.token = this.userService.getToken();
    const request = JSON.stringify({
      name: addUser.name,
      account: addUser.account,
      password: pwdMd5,
      phone: addUser.phone,
      remark: addUser.remark,
      status: addUser.status
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAddUser, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          ;
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
          ;
        }
      )
      .catch(this.handleError);
  }

  // 修改用户
  updateUserinfo(addUser: AddUser): Promise<any> {
    const pwdMd5 = Md5.hashStr(addUser.password).toString();
    const request = JSON.stringify({
      userId: addUser.userId,
      name: addUser.name,
      account: addUser.account,
      password: pwdMd5,
      phone: addUser.phone,
      remark: addUser.remark,
      status: addUser.status
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdateUser, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 删除用户
  removeUserinfo(addUser: AddUser): Promise<any> {
    const request = JSON.stringify({
      userId: addUser.userId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeleteUser, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          } else {
            return [false, body];
          }
        }
      )
      .catch(this.handleError);
  }

  // 分配角色
  allRole(addUser: AddUser, strEvent): Promise<any> {
    const request = JSON.stringify({
      userId: addUser.userId,
      roleIds: strEvent
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAllRole, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询角色
  getRoleInfo(page): Promise<any> {
    this.token = this.userService.getToken();
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
      criteria: {
        name: ''
      }
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlGetRole, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 获取已选择的角色
  selRoleId(addUser: AddUser): Promise<any> {
    const request = JSON.stringify({
      userId: addUser.userId,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlSureId, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
